<?php

/**
 * 分页导航条
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-09
 */

namespace app\common\logic;

use fw\base\Rout;
use fw\tool\Url;

class Page
{
    private $_conf = [
        'current_page' => 0,     // 当前页码
        'page_total'   => 0,     // 总页数
        'list_count'   => 0,     // 总条数
        'controller'   => '',    // 当前控制器
        'method'       => '',    // 当前方法
        'param'        => [],    // 额外参数
    ];

    public function __construct($conf = [])
    {
        $this->_conf['controller'] = Rout::gi()->currentController;
        $this->_conf['method'] = Rout::gi()->currentMethod;

        // 初始化配置项
        $this->_conf = array_merge($this->_conf, $conf);
    }

    /**
     * 生成URL
     *
     * @param int $page 当前页码
     *
     * @return string
     */
    private function _url($page)
    {
        $param = array_merge($this->_conf['param'], ['page' => $page]);
        $url = Url::to($this->_conf['controller'] . '/' . $this->_conf['method'], $param);

        return $url;
    }

    /**
     * 生成分页导航条
     *
     * @return string
     */
    public function show()
    {
        // 如果只有一页则直接返回
        if ($this->_conf['page_total'] <= 1) {
            return '';
        }

        /* 上一页 */
        $last_page = $this->_conf['current_page'] - 1;
        $last_page_html = '<a href="javascript:;">&lt</a>';
        if ($this->_conf['current_page'] > 1) {
            $last_page_html = '<a href="' . $this->_url($last_page) . '">&lt</a>';
        }

        /* 下一页 */
        $next_page = $this->_conf['current_page'] + 1;
        $next_page_html = '<a href="javascript:;">&gt</a>';
        if ($this->_conf['current_page'] < $this->_conf['page_total']) {
            $next_page_html = '<a href="' . $this->_url($next_page) . '">&gt</a>';
        }

        /* 分页视图 */
        $html = <<<EOT
<ul>
    <li>
        <span>共{$this->_conf['list_count']}条 {$this->_conf['current_page']}/{$this->_conf['page_total']}页</span>
    </li>
    <li>
        {$last_page_html}
    </li>
    <li>
        {$next_page_html}
    </li>
    <li>
        <form>
            <input type="hidden" name="c" value="{$this->_conf['controller']}">
            <input type="hidden" name="m" value="{$this->_conf['method']}">
            <span>跳转到</span>
            <input type="text" name="page" value="{$this->_conf['current_page']}">
            <input type="submit" value="go">
        </form>
    </li>
</ul>
EOT;

        return $html;
    }
}
